import requests
import time

class PrometheusClient:
    def __init__(self, server_url: str):
        self.server_url = server_url

    def query_range(self, query_exp, start_time, end_time, step):
        query_url = "{api_uri}/query_range?query={resource_name}" \
                    "&start={start_time}&end={end_time}&step={step}".format(
            api_uri=self.server_url , resource_name=query_exp,
            start_time=start_time, end_time=end_time, step=step)

        try:
            print("PrometheusClient", query_url)
            response = requests.get(query_url)
            print("PrometheusClient response ", response.json())
            return response.json()
        except Exception as error:
            print(error)
            return None

    def query(self, query_exp):
        query_url = "{api_uri}/query?query={resource_name}".format(
            api_uri=self.server_url , resource_name=query_exp)

        try:
            response = requests.get(query_url)
            return response.json()
        except Exception as error:
            print(error)
            return None

def query_prometheus_resource(cluster_prometheus_server_uri, query_exp):
    current_time = time.time()
    api_uri = "{}/api/v1".format(cluster_prometheus_server_uri)

    query_url = "{api_uri}/query_range?query={resource_name}" \
                "&start={start_time}&end={end_time}&step={step}".format(
                    api_uri=api_uri, resource_name= query_exp,
                    start_time=current_time, end_time=current_time, step=1 )

    try:
        print(query_url)
        headers = {'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0'}
        response = requests.get(query_url, headers=headers)
        return response.json()
    except Exception as error:
        print(error)
        return None


def query_range_prometheus_resource(cluster_prometheus_server_uri, query_exp, start_time, end_time, step=60):
    api_uri = "{}/api/v1".format(cluster_prometheus_server_uri)

    query_url = "{api_uri}/query_range?query={resource_name}" \
                "&start={start_time}&end={end_time}&step={step}".format(
                            api_uri=api_uri, resource_name= query_exp,
                            start_time=start_time, end_time=end_time, step=step)

    try:
        print(query_url)
        headers = {'User-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0'}
        response = requests.get(query_url, headers=headers)
        return response.json()
    except Exception as error:
        print(error)
        return None

